package com.yanchangapp.base;


import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.yanchangapp.BuildConfig;
import com.zxl.baselib.baseapp.AppManager;
import com.zxl.baselib.ui.base.BaseObserver;
import com.zxl.baselib.ui.base.ExceptionHandle;
import com.zxl.baselib.util.ui.UIUtils;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.ui.activity.base.LoginActivity;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;


/**
 *
 * @author 张先磊
 * @date 2018/4/10
 *
 * 含有token的retrofit
 * 看来这个只会执行一次啊 呵呵呵...
 */

public class WithHeadClient {
    // 这里的token是从数据库中获得的-------------
    private String token = "";
    private static final String TAG = "WithHeadClient";

    public OkHttpClient getClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder().
                readTimeout(60, TimeUnit.SECONDS);

        // -------- 在这里获得 token,通过数据库缓存 ********-----------
        if (BuildConfig.DEBUG) {
            // Log信息拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //设置 Debug Log 模式
            builder.addInterceptor(loggingInterceptor);
        }

        // todo 进行下一阶段的测试...
        token = UserCache.getAuthorization();
        Log.e("全局", "getClient: "+token);
        if (!TextUtils.isEmpty(token)){
            builder.addInterceptor(chain -> {
                Request.Builder request = chain.request().newBuilder();
                request.addHeader("Authorization", token);
                Log.e("拦截器", "intercept: "+token );
                Response proceed = chain.proceed(request.build());
                //如果token过期 再去重新请求token 然后设置token的请求头 重新发起请求 用户无感
                if (isTokenExpired(proceed)){
                    Log.e("拦截器", "=====重新登录====" );
                    doLogout();
                    return null;
                }
                return proceed;
            });
        }
        return builder.build();
    }

    private void doLogout(){
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            UserCache.clear();
            emitter.onNext(true);
            emitter.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        AppManager.getAppManager().finishAllActivity();
                        Intent intent = new Intent(UIUtils.getContext(), LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        UIUtils.getContext().startActivity(intent);
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {

                    }
                });
    }

    /**
     * 判断是否有网络
     *
     * @return 返回值
     */
    /**
     * 根据Response，判断Token是否失效
     * 401表示token过期
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        Log.e("状态码",response.code()+"---------------------");
        Log.e("状态码","我在这里啊..."+"---------------------");
        if (response.code() == 401) {
            return true;
        }
        return false;
    }
}
